/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.query.user;

import com.sfkj.walk.api.query.user.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.MetaDataConstants;
import org.axonframework.messaging.annotation.MetaDataValue;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Component
public class UserQueryService {

    private final UserRepository userRepository;
    private final SocialAccountRepository socialAccountRepository;

    @QueryHandler
    public Boolean handle(final PhoneIsExistsQuery query) {
        SocialAccount socialAccount = socialAccountRepository.findByOpenId(query.getPhone());
        return Objects.nonNull(socialAccount);
    }

    @QueryHandler
    public SocialAccount handle(final SocialAccountOneByPredicateQuery query) {
        return socialAccountRepository.findOne(query.getPredicate());
    }

    @QueryHandler
    public User handle(final UserOneByPredicateQuery query) {
        return userRepository.findOne(query.getPredicate());
    }

    @QueryHandler
    public User handle(final CurrentUserQuery query, @MetaDataValue(MetaDataConstants.CURRENT_USER_ID) String currentUserId) {
        return userRepository.findOne(currentUserId);
    }

    @QueryHandler
    public Iterable<User> handle(final UserAllByPredicateQuery query) {
        if (Objects.nonNull(query.getPageable())) {
            return userRepository.findAll(query.getPredicate(), query.getPageable());
        }
        if (Objects.nonNull(query.getSort())) {
            return userRepository.findAll(query.getPredicate(), query.getSort());
        }

        return userRepository.findAll(query.getPredicate());
    }

}
